import requests
from flask_assets import Bundle, Environment
from webassets.filter import Filter, register_filter


class JsFilter(Filter):
    name = "js_compress"

    def output(self, _in, out, **kwargs):
        js = _in.read()
        req = requests.post("https://javascript-minifier.com/raw", {"input": js})
        out.write(req.text)

    def input(self, _in, out, **kwargs):
        js = _in.read()
        out.write(js)


register_filter(JsFilter)


def compile_static_assets(app):

    assets = Environment(app)
    Environment.auto_build = True
    Environment.debug = False

    style_css_bundle = Bundle(
        "src/css/style.css",
        filters="cssmin",
        output="dist/css/style.min.css",
        extra={"rel": "stylesheet/css"},
    )

    stats_chart_js_bundle = Bundle(
        "src/js/stats_chart.js",
        filters="js_compress",
        output="dist/js/stats_chart.min.js",
    )

    home_chart_js_bundle = Bundle(
        "src/js/home_chart.js",
        filters="js_compress",
        output="dist/js/home_chart.min.js",
    )

    assets.register("style_css_bundle", style_css_bundle)
    assets.register("stats_chart_js_bundle", stats_chart_js_bundle)
    assets.register("home_chart_js_bundle", home_chart_js_bundle)

    style_css_bundle.build()
    stats_chart_js_bundle.build()
    home_chart_js_bundle.build()

    return assets
